import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Http } from '@angular/http';
import { LeftSidebarService } from '../sidebar/left-sidebar-service';
import { BaseComponet } from '../BaseComponet';
import { Subscription } from 'rxjs';

declare var $: any;
@Component({
    selector: 'app-privilege-management',
    templateUrl: './privilege-management.component.html',
    styleUrls: ['./privilege-management.component.css']
})
export class PrivilegeManagementComponent extends BaseComponet
    implements OnInit {
    public isOnShow = true;
    public privilegeId: String;
    public privilegeName: String;
    public subLinks: any[];
    public pageNo: number;
    public pageSize: number;
    public orderBy: String;
    public orderType: String;
    public searchKeywords: String;
    public total: number;
    public privileges: any[];
    public totalPages: number;
    public parentId: String;
    public displayUpBottonStyle: String;
    public toAddPrivilegeName: String;
    public toAddIsLocked: boolean;
    public toAddPrivilegeCode: String;
    public toAddSimpleUrl: String;
    public toAddRequestMethod: String;
    public toAddIsMenu: boolean;
    public toAddIdPath: String;
    public toAddIconClass: String;
    public toAddIconType: String;
    public toAddAb: String;
    public toAddCollapse: String;
    public toAddSortValue: String;
    public checkedPrivilegeIds: any[];
    public checkedAll: boolean;
    public toModifyPrivilegeId: String;
    public toModifyPrivilegeName: String;
    public toModifyPrivilegeCode: String;
    public toModifySimpleUrl: String;
    public toModifyRequestMethod: String;
    public toModifyIsMenu: boolean;
    public toModifyIdPath: String;
    public toModifyIconClass: String;
    public toModifyIconType: String;
    public toModifyAb: String;
    public toModifyCollapse: String;
    public toModifySortValue: String;
    public toModifyIsLocked: boolean;
    public toMovePrivilegeTrees: any[];
    public moveToPrivilegeId: String;
    public menus: any[];
    public showAdd = false;
    public showModify = false;
    public showMoveTo = false;
    public showDelete = false;
    public showLock = false;
    public showUnlock = false;
    public displayPrivilegeTrees: any[];
    public menuChangeSubscription: Subscription;
    constructor(
        public routerInfo: ActivatedRoute,
        public http: Http,
        public router: Router,
        public leftSidebarService: LeftSidebarService
    ) {
        super();
    }
    switchButtons() {
        this.menus = JSON.parse(sessionStorage.getItem('menus'));
        if (this.menus.indexOf('manager:privilege.back.add') > -1) {
            this.showAdd = true;
        } else {
            this.showAdd = false;
        }
        if (this.menus.indexOf('manager:privilege.back.modify') > -1) {
            this.showModify = true;
        } else {
            this.showModify = false;
        }
        if (this.menus.indexOf('manager:privilege.back.move-to') > -1) {
            this.showMoveTo = true;
        } else {
            this.showMoveTo = false;
        }
        if (this.menus.indexOf('manager:privilege.back.delete-by-ids') > -1) {
            this.showDelete = true;
        } else {
            this.showDelete = false;
        }
        if (this.menus.indexOf('manager:privilege.back.lock') > -1) {
            this.showLock = true;
        } else {
            this.showLock = false;
        }
        if (this.menus.indexOf('manager:privilege.back.unlock') > -1) {
            this.showUnlock = true;
        } else {
            this.showUnlock = false;
        }
    }
    ngOnDestroy() {
        this.isOnShow = false;
        console.log('ngOnDestroy()');
        $('.popover').remove();
        this.menuChangeSubscription.unsubscribe();
    }
    ngOnInit() {
        this.toMovePrivilegeTrees = [];
        this.displayPrivilegeTrees = [];
        $('[data-toggle="popover"]').popover();
        this.switchButtons();
        this.menuChangeSubscription = this.leftSidebarService.menusChange.subscribe(
            command => {
                this.switchButtons();
            }
        );
        // $(document).on('show.bs.modal', '.modal', function () {
        //   $(this).draggable();
        //   $(this).css('overflow-y', 'scroll');
        //   // 防止出现滚动条，出现的话，你会把滚动条一起拖着走的
        // });
        // $('[data-toggle="popover"]').popover();
        this.routerInfo.params.subscribe((params: Params) => {
            this.privilegeId = params['privilegeId'];
            this.pageNo = params['pageNo'];
            this.pageSize = params['pageSize'];
            this.orderBy = params['orderBy'];
            this.orderType = params['orderType'];
            this.searchKeywords = params['searchKeywords'];
            if (this.privilegeId == null) {
                this.privilegeId = '';
            }
            if (this.orderBy == null) {
                this.orderBy = '';
            }
            if (this.orderType == null) {
                this.orderType = '';
            }
            if (this.searchKeywords == null) {
                this.searchKeywords = '';
            }
            if (this.pageNo == null) {
                this.pageNo = 1;
            } else {
                this.pageNo = parseInt(params['pageNo'], 10);
            }
            if (this.pageSize == null) {
                this.pageSize = parseInt(localStorage.getItem('pageSize'), 10);
                if (this.pageSize == null || isNaN(this.pageSize)) {
                    this.pageSize = 30;
                }
            } else {
                localStorage.setItem('pageSize', '' + this.pageSize);
            }
            this.displayData();
        });
    }
    displayData() {
        this.checkedPrivilegeIds = [];
        this.checkedAll = false;
        this.showLoading();
        if (
            this.privilegeId == null ||
            this.privilegeId === '' ||
            this.privilegeId === '-1'
        ) {
            this.privilegeId = '-1';
            this.parentId = null;
            this.displayUpBottonStyle = 'none';
            this.privilegeName = '所有权限项';
            this.subLinks = [];
            this.subLinks[0] = {
                privilegeId: '',
                privilegeName: '所有权限项'
            };
            this.http
                .get(
                    '/user/back/privilege/page/parent-id--1/search-' +
                        this.searchKeywords.toString() +
                        '/order-by-' +
                        this.orderBy +
                        '/order-type-' +
                        this.orderType +
                        '/page-no/' +
                        this.pageNo +
                        '/page-size/' +
                        this.pageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        if (this.isOnShow) {
                            this.hideLoading();
                        }
                        this.total = result.total;
                        this.privileges = result.list;
                        this.totalPages = result.totalPages;
                        this.orderBy = result.orderBy;
                        this.orderType = result.orderType;
                    },
                    error => {}
                );
        } else {
            this.http
                .get('/user/back/privilege/path/' + this.privilegeId)
                .map(result => result.json())
                .subscribe(
                    result => {
                        this.displayUpBottonStyle = '';
                        this.privilegeName = result.privilegeName;
                        this.subLinks = result.privilegePath;
                        if (this.subLinks.length > 1) {
                            this.parentId = this.subLinks[
                                this.subLinks.length - 2
                            ].privilegeId;
                        } else if (this.subLinks.length > 0) {
                            this.parentId = '-1';
                        } else {
                            this.parentId = null;
                        }
                        this.subLinks.unshift({
                            privilegeId: '',
                            privilegeName: '所有权限项'
                        });
                    },
                    error => {
                        this.router.navigate(['privilege-management']);
                    }
                );
            this.http
                .get(
                    '/user/back/privilege/page/parent-id-' +
                        this.privilegeId +
                        '/search-' +
                        this.searchKeywords.toString() +
                        '/order-by-' +
                        this.orderBy +
                        '/order-type-' +
                        this.orderType +
                        '/page-no/' +
                        this.pageNo +
                        '/page-size/' +
                        this.pageSize
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        if (this.isOnShow) {
                            this.hideLoading();
                        }
                        this.total = result.total;
                        this.privileges = result.list;
                        this.totalPages = result.totalPages;
                        this.orderBy = result.orderBy;
                        this.orderType = result.orderType;
                    },
                    error => {
                        this.router.navigate(['privilege-management']);
                    }
                );
        }
    }
    upToParent(parentId) {
        if (parentId == null) {
            alert('已经到达最上级');
            return;
        }
        this.privilegeId = parentId;
        this.pageNo = 1;
        this.router.navigate([
            'privilege-management/' +
                this.privilegeId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    sort(orderBy) {
        if (this.orderBy === orderBy) {
            if (this.orderType === 'asc') {
                this.orderType = 'desc';
            } else {
                this.orderType = 'asc';
            }
        } else {
            this.orderBy = orderBy;
        }
        this.router.navigate([
            'privilege-management/' +
                this.privilegeId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    clearKeywords() {
        this.searchKeywords = '';
    }
    setPageSize(pageSize) {
        this.pageSize = pageSize;
        this.pageNo = 1;
        localStorage.setItem('pageSize', '' + this.pageSize);
        this.router.navigate([
            'privilege-management/' +
                this.privilegeId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    goToPage(pageNo) {
        this.pageNo = pageNo;
        this.router.navigate([
            'privilege-management/' +
                this.privilegeId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    toAdd() {
        this.toAddIsLocked = false;
        this.toAddPrivilegeName = '';
        this.toAddPrivilegeCode = '';
        this.toAddSimpleUrl = '';
        this.toAddRequestMethod = '';
        this.toAddIsMenu = null;
        this.toAddIdPath = '';
        this.toAddIconClass = '';
        this.toAddIconType = '';
        this.toAddAb = '';
        this.toAddCollapse = '';
        this.toAddSortValue = '';
        $('#addModal').modal('show');
    }
    add() {
        this.http
            .post('/user/back/privilege/', {
                privilegeName: this.toAddPrivilegeName,
                privilegeCode: this.toAddPrivilegeCode,
                isLocked: this.toAddIsLocked,
                parentId: this.privilegeId,
                simpleUrl: this.toAddSimpleUrl,
                requestMethod: this.toAddRequestMethod,
                isMenu: this.toAddIsMenu,
                idPath: this.toAddIdPath,
                iconClass: this.toAddIconClass,
                iconType: this.toAddIconType,
                ab: this.toAddAb,
                collapse: this.toAddCollapse,
                sortValue: this.toAddSortValue
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    $('#addModal').modal('hide');
                    this.goToPage(1);
                    this.displayData();
                    this.leftSidebarService.refresh.emit('privilegeManagement');
                },
                error => {}
            );
    }
    checkAll() {
        if (this.checkedAll === false) {
            this.checkedAll = true;
            this.checkedPrivilegeIds = [];
            for (let i = 0; i < this.privileges.length; i++) {
                this.checkedPrivilegeIds.push(this.privileges[i].privilegeId);
            }
            $('.privilege-list').prop('checked', true);
        } else {
            this.checkedAll = false;
            this.checkedPrivilegeIds = [];
            $('.privilege-list').prop('checked', false);
        }
    }
    check(privilegeId) {
        this.checkedPrivilegeIds = [];
        if (
            $('.privilege-list').length === $('.privilege-list:checked').length
        ) {
            this.checkedAll = true;
        } else {
            this.checkedAll = false;
        }
        const checkedprivilegeIds = this.checkedPrivilegeIds;
        $('.privilege-list:checked').each(function() {
            checkedprivilegeIds.push($(this).val());
        });
    }
    toDelete() {
        if (this.checkedPrivilegeIds.length <= 0) {
            alert('请先选中需要删除的权限项！');
            return;
        }
        if (confirm('确定删除选中的权限项吗？')) {
            this.http
                .delete(
                    '/user/back/privilege/by-ids/' +
                        this.checkedPrivilegeIds.join('-')
                )
                .map(result => result.json())
                .subscribe(
                    result => {
                        alert(result.message);
                        this.displayData();
                        this.leftSidebarService.refresh.emit(
                            'privilegeManagement'
                        );
                    },
                    error => {
                        this.displayData();
                    }
                );
        }
    }
    toModify() {
        if ($('.privilege-list:checked').length > 1) {
            alert('一次只能修改一个权限项！');
            return;
        }
        if ($('.privilege-list:checked').length === 0) {
            alert('请选择需要修改的权限项！');
            return;
        }
        const privilegeId = $('.privilege-list:checked').val();
        for (let i = 0; i < this.privileges.length; i++) {
            if (this.privileges[i].privilegeId === privilegeId) {
                this.toModifyPrivilegeId = privilegeId;
                this.toModifyPrivilegeName = this.privileges[i].privilegeName;
                this.toModifyPrivilegeCode = this.privileges[i].privilegeCode;
                this.toModifyIsLocked = this.privileges[i].isLocked;
                this.toModifySimpleUrl = this.privileges[i].simpleUrl;
                this.toModifyRequestMethod = this.privileges[i].requestMethod;
                this.toModifyIsMenu = this.privileges[i].isMenu;
                this.toModifyIdPath = this.privileges[i].idPath;
                this.toModifyIconClass = this.privileges[i].iconClass;
                this.toModifyIconType = this.privileges[i].iconType;
                this.toModifyAb = this.privileges[i].ab;
                this.toModifyCollapse = this.privileges[i].collapse;
                this.toModifySortValue = this.privileges[i].sortValue;
                console.log('this.toModifyIsMenu', this.toModifyIsMenu);
                break;
            }
        }
        $('#modifyModal').modal('show');
    }
    modify() {
        this.http
            .put('/user/back/privilege/' + this.toModifyPrivilegeId, {
                privilegeName: this.toModifyPrivilegeName,
                privilegeCode: this.toModifyPrivilegeCode,
                isLocked: this.toModifyIsLocked,
                parentId: this.privilegeId,
                privilegeId: this.toModifyPrivilegeId,
                simpleUrl: this.toModifySimpleUrl,
                requestMethod: this.toModifyRequestMethod,
                isMenu: this.toModifyIsMenu,
                idPath: this.toModifyIdPath,
                iconClass: this.toModifyIconClass,
                iconType: this.toModifyIconType,
                ab: this.toModifyAb,
                collapse: this.toModifyCollapse,
                sortValue: this.toModifySortValue
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    $('#modifyModal').modal('hide');
                    this.displayData();
                    this.leftSidebarService.refresh.emit('privilegeManagement');
                },
                error => {}
            );
    }
    toMove() {
        if (
            this.checkedPrivilegeIds == null ||
            this.checkedPrivilegeIds.length === 0
        ) {
            alert('请选择需要移动的权限项');
            return;
        }
        $('#moveToModal').modal('show');
        // this.toMovePrivilegeTrees = JSON.parse(localStorage.getItem('privilege-trees'));
        this.http
            .get('/user/back/privilege/trees')
            .map(result => result.json())
            .subscribe(
                result => {
                    this.toMovePrivilegeTrees = result.trees;
                    localStorage.setItem(
                        'privilege-trees',
                        JSON.stringify(this.displayPrivilegeTrees)
                    );
                },
                error => {
                    this.toMovePrivilegeTrees = null;
                }
            );
    }
    move() {
        if (
            this.checkedPrivilegeIds == null ||
            this.checkedPrivilegeIds.length === 0
        ) {
            alert('请选择需要移动的权限项');
            return;
        }
        this.moveToPrivilegeId = $(
            'input[name="moveToPrivilegeId"]:checked'
        ).val();
        if (this.moveToPrivilegeId == null) {
            alert('请选择目标权限项！');
            return;
        }
        this.http
            .put('/user/back/privilege/move-to/' + this.moveToPrivilegeId, {
                privilegeIds: this.checkedPrivilegeIds
            })
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    $('#moveToModal').modal('hide');
                    this.displayData();
                    this.leftSidebarService.refresh.emit('privilegeManagement');
                },
                error => {}
            );
    }
    displayTree() {
        $('#displayTreeModal').modal('show');
        // this.displayPrivilegeTrees = JSON.parse(localStorage.getItem('privilege-tree'));
        this.http
            .get('/user/back/privilege/trees')
            .map(result => result.json())
            .subscribe(
                result => {
                    this.displayPrivilegeTrees = result.trees;
                    localStorage.setItem(
                        'privilege-trees',
                        JSON.stringify(this.displayPrivilegeTrees)
                    );
                },
                error => {
                    this.displayPrivilegeTrees = null;
                }
            );
    }
    goToNode(privilegeId) {
        $('#displayTreeModal').modal('hide');
        this.privilegeId = privilegeId;
        this.pageNo = 1;
        this.router.navigate([
            'privilege-management/' +
                this.privilegeId +
                '/' +
                this.pageNo +
                '/' +
                this.pageSize +
                '/' +
                this.orderBy +
                '/' +
                this.orderType +
                '/' +
                this.searchKeywords.toString()
        ]);
    }
    lock(privilegeId) {
        this.http
            .put('/user/back/privilege/' + privilegeId + '/lock', {})
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    this.displayData();
                },
                error => {}
            );
    }
    unlock(privilegeId) {
        this.http
            .put('/user/back/privilege/' + privilegeId + '/unlock', {})
            .map(result => result.json())
            .subscribe(
                result => {
                    alert(result.message);
                    this.displayData();
                },
                error => {}
            );
    }
}
